import 'package:flutter/material.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/core/models/delivery_status.dart';
import 'package:mall/core/models/order_detail.dart';
import 'package:mall/core/models/order_list.dart';
import 'package:mall/core/models/order_status.dart';
import 'package:mall/core/providers/pages/mine/order/order_detail_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/order/logistics_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 参数
class OrderDetailPageArgs {
  final int storeId;
  final String code;

  OrderDetailPageArgs(this.storeId, this.code);
}

/// 订单详情
class OrderDetailPage extends StatelessWidget {
  static const routeName = '/OrderDetailPage';
  final OrderDetailPageArgs args;

  OrderDetailPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => OrderDetailModel(
        Provider.of(context, listen: false),
        args.storeId,
        args.code,
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text('订单详情'),
        ),
        body: Consumer<OrderDetailModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ViewState.error:
                return Center(
                  child: Text(model.errorMessage),
                );
              case ViewState.success:
                return _SuccessWidget(
                  orderDetail: model.orderDetail,
                );
              default:
                return Container();
            }
          },
        ),
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final OrderDetail orderDetail;

  const _SuccessWidget({
    Key key,
    @required this.orderDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: _HeaderWidget(
            order: orderDetail.model,
          ),
        ),
        SliverFixedExtentList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return _ProductItemWidget(
                product: orderDetail.model.orderDetails[index],
              );
            },
            childCount: orderDetail.model.orderDetails.length,
          ),
          itemExtent: 76,
        ),
        SliverToBoxAdapter(
          child: _FooterWidget(order: orderDetail.model),
        ),
        SliverToBoxAdapter(
          child: Column(
            children: [
              SizedBox(height: 8.w),
              _OrderInfoWidget(order: orderDetail.model),
              SizedBox(height: 8.w),
              OrderAddressee(order: orderDetail.model),
            ],
          ),
        ),
        if (orderDetail.invoices.length > 0) ...[
          SliverToBoxAdapter(
            child: SizedBox(height: 12),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return _InvoiceItemWidget(
                  invoice: orderDetail.invoices[index],
                  isFirst: index == 0,
                  isLast: index == orderDetail.invoices.length - 1,
                );
              },
              childCount: orderDetail.invoices.length,
            ),
          )
        ],
      ],
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  final Order order;

  const _HeaderWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(12),
      color: Colors.white,
      margin: EdgeInsets.only(top: 8.w),
      child: Row(
        children: [
          Image.asset('assets/images/order/ic_line.png', width: 2),
          SizedBox(width: 6),
          Text('订单编号：${order.code}'),
        ],
      ),
    );
  }
}

class _ProductItemWidget extends StatelessWidget {
  final Product product;

  const _ProductItemWidget({
    Key key,
    @required this.product,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          SizedBox(width: 16),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: ImageNetwork(
              url: '${product.productImage}',
              width: 60,
              height: 60,
            ),
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${product.productName}',
                  style: TextStyle(color: Color(0xFF35353C), fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                Text('产品属性', style: TextStyle(color: Colors.grey, fontSize: 14)),
                Text.rich(
                  TextSpan(
                    style: TextStyle(color: Colors.grey, fontSize: 13),
                    children: product.priceVos
                        .map(
                          (e) => TextSpan(
                            text: " ${e.flag}",
                            style: TextStyle(fontSize: 6),
                            children: [
                              TextSpan(
                                text: "${e.pointCoinString}",
                                style: TextStyle(fontSize: 12),
                              ),
                            ],
                          ),
                        )
                        .toList(),
                  ),
                )
              ],
            ),
          ),
          Text(
            'x${product.quantity}',
            style: TextStyle(color: Color(0xFFAEAEAE), fontSize: 16),
          ),
          SizedBox(width: 16),
        ],
      ),
    );
  }
}

class _FooterWidget extends StatelessWidget {
  final Order order;

  const _FooterWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var totalQuantity = 0;
    order.orderDetails.forEach((product) {
      totalQuantity += product.quantity;
    });
    var status = order.orderStatusStr;
    if (order.orderStatus == OrderStatus.PAID) {
      if (order.deliveryStatus == DeliveryStatus.CONFIRMING ||
          order.deliveryStatus == DeliveryStatus.CONFIRMED) {
        status = order.deliveryStatusStr;
      }
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 86,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          SizedBox(height: 6),
          Text(
            '共$totalQuantity件 | $status',
            style: TextStyle(color: Color(0xFF747474), fontSize: 13),
          ),
          Row(
            children: [
              Expanded(
                child: Text('运费：', style: TextStyle(color: Color(0xFF747474))),
              ),
              Text('￥${order.paidFreight ?? 0}', style: TextStyle(color: Color(0xFF747474))),
            ],
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  order.orderStatus == OrderStatus.PAID ? '实付款：' : '应付款：',
                  style: TextStyle(color: Color(0xFF747474)),
                ),
              ),
              Text.rich(
                TextSpan(
                  style: TextStyle(color: Color(0xFFEA537A), fontSize: 15),
                  children: order.priceVos
                      .map(
                        (e) => TextSpan(
                          text: " ${e.flag}",
                          style: TextStyle(fontSize: 10),
                          children: [
                            TextSpan(
                              text: "${e.pointCoinString}",
                              style: TextStyle(fontSize: 15),
                            ),
                          ],
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class _InvoiceItemWidget extends StatelessWidget {
  final Invoice invoice;
  final bool isFirst;
  final bool isLast;

  _InvoiceItemWidget({
    Key key,
    @required this.invoice,
    @required this.isFirst,
    @required this.isLast,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(invoice.expressCompany),
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text('运单号：${invoice.expressNumber}'),
          Icon(Icons.keyboard_arrow_right),
        ],
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed(LogisticsPage.routeName, arguments: invoice);
  }
}

class _OrderInfoWidget extends StatelessWidget {
  final Order order;

  const _OrderInfoWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(12),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Image.asset('assets/images/order/ic_line.png', width: 2),
              SizedBox(width: 6),
              Text('订单信息', style: TextStyle(color: Colors.black))
            ],
          ),
          Divider(height: 24),
          Table(
            columnWidths: {0: FractionColumnWidth(.3)},
            children: [
              TableRow(
                children: [
                  _OrderInfoParamsWidget(title: '订单编号：'),
                  Text(order.code ?? '--', style: TextStyle(color: Colors.grey)),
                ],
              ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(title: '创建时间：'),
                  Text(order.createTime ?? '--', style: TextStyle(color: Colors.grey)),
                ],
              ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(title: '付款时间：'),
                  Text(order.payTime ?? '--', style: TextStyle(color: Colors.grey)),
                ],
              ),
              if (order.deliveryStatus == DeliveryStatus.CONFIRMING)
                TableRow(
                  children: [
                    _OrderInfoParamsWidget(title: '发货时间：'),
                    Text(order.deliveryTime ?? '', style: TextStyle(color: Colors.grey)),
                  ],
                ),
              if (order.deliveryStatus == DeliveryStatus.CONFIRMED)
                TableRow(
                  children: [
                    _OrderInfoParamsWidget(title: '收货时间：'),
                    Text(order.deliveryTime ?? '', style: TextStyle(color: Colors.grey)),
                  ],
                ),
              TableRow(
                children: [
                  _OrderInfoParamsWidget(title: '订单备忘：'),
                  Text(order.memo ?? '--', style: TextStyle(color: Colors.grey)),
                ],
              ),
            ],
          )
        ],
      ),
    );
  }
}

class _OrderInfoParamsWidget extends StatelessWidget {
  final String title;

  const _OrderInfoParamsWidget({
    Key key,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 32,
      child: Text(
        title,
        style: TextStyle(color: Colors.black87),
      ),
    );
  }
}

/// 订单收件人
class OrderAddressee extends StatelessWidget {
  final Order order;

  OrderAddressee({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(12),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset('assets/images/order/ic_line.png', width: 2),
              SizedBox(width: 6),
              Text('收件人', style: TextStyle(color: Colors.black))
            ],
          ),
          Divider(height: 24),
          Row(
            children: [
              Text("${order.linkMan}"),
              SizedBox(width: 4),
              Text("${_hidePhone(order.contactPhone)}"),
            ],
          ),
          SizedBox(height: 8),
          Text("地址：${order.fullAddress}", style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }

  /// 隐藏手机号中间四位数
  String _hidePhone(String phone) {
    if (phone == null || phone.isEmpty || phone.length < 11) {
      return phone;
    }
    return phone.replaceRange(3, 7, "****");
  }
}
